# -*- coding: utf-8 -*-
# @author: edgardeng
# @date:   2021-05-08
# @file:   
"""
 基于传输层TCP/IP协议接口socket实现的TCP发送json格式数据

 测试客户端-短连接
"""
#
import time
from socket import *

if __name__ == '__main__':

    # 基础参数(这里填写要发送到的服务端地址端口)
    HOST = '127.0.0.1'  # or 'localhost'
    PORT = 21726
    buf_size = 2048
    ADDR = (HOST, PORT)

    tcpCliSock = socket(AF_INET, SOCK_STREAM)  # 创建socket
    tcpCliSock.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)  # 在客户端开启心跳维护 (socket会自己维护)

    tcpCliSock.connect(ADDR)

    for i in range(10):
        # 用户控制台输入数据
        data_input = input('[client]: input message to send >')
        if not data_input:
            print('error')
            continue

        # 客户端发送给服务端
        tcpCliSock.send(data_input.encode())
        data_receive = tcpCliSock.recv(buf_size)
        if not data_receive:
            print('error')
        print('[client]: {}'.format(data_receive.decode('utf-8')))

        time.sleep(1)
        # 一次短连接,三次握手结束,任何一方都可以发起close
    tcpCliSock.close()
